package com.joy.web.base.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joy.common.constant.CommonCons;
import com.joy.common.constant.PageCons;
import com.joy.common.model.DateTablePage;
import com.joy.common.model.vo.UserInfoVO;
import com.joy.common.utils.AntiSQLFilter;
import com.joy.common.utils.TypeUtils;
import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

/**
 * @ClassName: BaseController
 * @Description: 通用 Controlller
 * @Author: yjzhao
 * @Create: 2019-09-09  13:14
 **/
@Slf4j
public class BaseController {
    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;



    /**
     * 获取分页对象
     *
     * @return
     */
    protected <T> Page<T> getPage() {
        return getPage(false);
    }

    /**
     * 获取分页对象
     *
     * @param openSort
     * @return
     */
    protected <T> Page<T> getPage(boolean openSort) {
        int index = 1;
        // 页数
        Integer cursor = TypeUtils.castToInt(request.getParameter(PageCons.PAGE_PAGE), index);
        // 分页大小
        Integer limit = TypeUtils.castToInt(request.getParameter(PageCons.PAGE_ROWS), PageCons.DEFAULT_LIMIT);
        // 是否查询分页
        Boolean searchCount = TypeUtils.castToBoolean(request.getParameter(PageCons.SEARCH_COUNT), true);
        limit = limit > PageCons.MAX_LIMIT ? PageCons.MAX_LIMIT : limit;
        Page<T> page = new Page<>(cursor, limit, searchCount);
        if (openSort) {
            page.setAsc(getParameterSafeValues(PageCons.PAGE_ASCS));
            page.setDesc(getParameterSafeValues(PageCons.PAGE_DESCS));
        }
        return page;
    }

    /**
     * 获取分页对象
     *
     * @return
     */
    protected <T> Page<T> getDataTablePage() {
        return getDataTablePage(false);
    }

    /**
     * 获取分页对象
     *
     * @param openSort
     * @return
     */
    protected <T> Page<T> getDataTablePage(boolean openSort) {
        int start = TypeUtils.castToInt(request.getParameter(PageCons.PAGE_START), 0);
        int length = TypeUtils.castToInt(request.getParameter(PageCons.PAGE_LENGTH), PageCons.DEFAULT_LIMIT);
        long cursor = start/length + 1;

        // 是否查询分页
        length = length > PageCons.MAX_LIMIT ? PageCons.MAX_LIMIT : length;
        Page<T> page = new Page<>(cursor, length, true);
        if (openSort) {
            page.setAsc(getParameterSafeValues(PageCons.PAGE_ASCS));
            page.setDesc(getParameterSafeValues(PageCons.PAGE_DESCS));
        }
        return page;
    }

    protected <T> DateTablePage<T> getDataTableRtn(IPage<T> iPage){
        DateTablePage dateTablePage = new DateTablePage();
        Integer draw = TypeUtils.castToInt(request.getParameter("draw"), 0);

        if (draw != null) {
            dateTablePage.setDraw(draw);
            dateTablePage.setData(iPage.getRecords());
            dateTablePage.setRecordsFiltered(iPage.getTotal());
            dateTablePage.setRecordsTotal(iPage.getTotal());
        }
        return dateTablePage;
    }

    /**
     * 获取安全参数(SQL ORDER BY 过滤)
     *
     * @param parameter
     * @return
     */
    protected String[] getParameterSafeValues(String parameter) {
        return AntiSQLFilter.getSafeValues(request.getParameterValues(parameter));
    }

    /**
     * @Description 获取用户详情信息
     * @param
     * @return
     * @Author yjzhao
     * @Date 2019/9/17 21:03
     **/
    protected Optional<UserInfoVO> getUserInfo() {
        Optional<String> userNmOp = this.getUserNm();
        if (!userNmOp.isPresent()) {
            return Optional.empty();
        }
        Cache userInfosCache = CacheManager.getInstance().getCache(CommonCons.MyCache.USERINFOS);
        Element userInfoEle = userInfosCache.get(userNmOp.get());
        if (userInfoEle == null) {
            return Optional.empty();
        }
        UserInfoVO userInfoVO = (UserInfoVO) userInfoEle.getObjectValue();

        return Optional.of(userInfoVO);
    }

    /**
     * @Description 获取用户名称
     * @return
     * @Author yjzhao
     * @Date 2019/9/17 21:09
     **/
    protected Optional<String> getUserNm() {
        Subject subject = SecurityUtils.getSubject();
        if (subject == null || subject.getPrincipal() == null) {
            return Optional.empty();
        }
        String userNm = (String)subject.getPrincipal();
        return Optional.of(userNm);
    }

    /**
     * @Description 获取 userId
     * @return
     * @Author yjzhao
     * @Date 2019/9/17 21:09
     **/
    protected Optional<String> getUserId() {
        Optional<UserInfoVO> userInfoOp = this.getUserInfo();
        if (!userInfoOp.isPresent()) {
            return Optional.empty();
        }
        return Optional.of(userInfoOp.get().getUserId());
    }
}
